package com.linchuan.concurrency;

import java.io.PrintWriter;
import java.util.concurrent.BlockingQueue;

public class LogService {
  private final BlockingQueue<String> queue;
  private final LoggerThread loggerThread;
  private final PrintWriter writer;
  private boolean isShutdown;
  private int reservations;

  public void start() {
    loggerThread.start();
  }

  public void stop() {
    synchronized (this) {
      isShutdown = true;
    }
    loggerThread.interrupt();
  }

  public void log(String msg) throws InterruptedException {
    synchronized (this) {
      if (isShutdown) throw new IllegalStateException("has shutdown LogService");
      ++reservations;
    }
    queue.put(msg);
  }

  private class LoggerThread extends Thread {
    @Override
    public void run() {
      try {
        while (true) {
          try {
            synchronized (LogService.this) {
              if (isShutdown && reservations == 0) {
                break;
              }
            }
            String msg = queue.take();
            synchronized (LogService.this) {
              --reservations;
            }
            writer.println(msg);
          } catch (InterruptedException e) {
            /*
            retry
            这个地方的作用是：出现中断请求就到下一个try，应该是满足break的条件再退出
            */

          }
        }
      } finally {
        writer.close();
      }
    }
  }
}
